package com.zhiche.lisa.oms.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.common.collect.Sets;
import com.zhiche.lisa.core.enums.TableStatusEnum;
import com.zhiche.lisa.core.supports.BaseException;
import com.zhiche.lisa.core.utils.Account.JwtAccountVO;
import com.zhiche.lisa.core.utils.Account.JwtTokenUtil;
import com.zhiche.lisa.core.utils.HttpClientUtil;
import com.zhiche.lisa.core.utils.SnowFlakeId;
import com.zhiche.lisa.oms.dao.model.*;
import com.zhiche.lisa.oms.dto.HuiyuncheCancleDTO;
import com.zhiche.lisa.oms.dto.HuiyuncheShipInfoDTO;
import com.zhiche.lisa.oms.dto.OriginationDTO;
import com.zhiche.lisa.oms.dto.PriceIncomingDTO;
import com.zhiche.lisa.oms.enums.CodePrefixEnum;
import com.zhiche.lisa.oms.service.*;
import com.zhiche.lisa.oms.vo.LocationVo;
import com.zhiche.lisa.tms.dao.model.*;
import com.zhiche.lisa.tms.dto.OrderAssignDTO;
import com.zhiche.lisa.tms.dto.PricePurchaseDTO;
import com.zhiche.lisa.tms.service.*;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.assertj.core.util.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

@Service
public class HuiyuncheServiceImpl implements IHuiyuncheService {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private IOrderService orderService;
    @Autowired
    private ILocationService locationService;
    @Autowired
    private SnowFlakeId snowFlakeId;
    @Autowired
    private IOrderItemService itemService;
    @Autowired
    private IOrderContactService contactService;
    @Autowired
    private IOrderLocationService orderLocationService;
    @Autowired
    private IShipOrderService shipOrderService;
    @Autowired
    private IOrderAssignService assignService;
    @Autowired
    private IShipTaskService taskService;
    @Autowired
    private IShipmentDetailService shipmentDetailService;
    @Autowired
    private IShipmentService shipmentService;
    @Autowired
    private IShipOrderItemService shipOrderItemService;


    @Value("${erp.getNewestShipByLicenseUrl}")
    private String getNewestShipByLicenseUrl;
    //连接超时时间
    @Value("${erp.socketTimeout}")
    private int socketTimeout;
    @Value("${erp.rmtILSShipUrl}")
    private String rmtILSShipUrl;
    @Value("${lisa.lspm.authedCarrierPlateURL}")
    private String authedCarrierPlateURL;
    @Value("${uaa.getTentUrl}")
    private String getTentUrl;
    @Value("${security.oauth2.client.access-token-uri}")
    private String getTokenUrl;
    @Value("${security.oauth2.client.clientId}")
    private String getClinetId;
    @Value("${security.oauth2.client.clientSecret}")
    private String getClientSecret;
    @Value("${lisa.lspm.getCarrierInfoByPlate}")
    private String getCarrierInfoByPlate;
    @Value("${integration.getPriceAndMilesUrl}")
    private String getPriceAndMilesUrl;
    @Value("${integration.url}")
    private String integrationUrl;
    @Value("${lisa.bms.insertPriceIncomingUrl}")
    private String insertPriceIncomingUrl;
    @Value("${lisa.bms.updateIncomingPriceByTaskCodeUrl}")
    private String updateIncomingPriceByTaskCodeUrl;
    @Value("${lisa.bms.deletePriceIncomingUrl}")
    private String deletePriceIncomingUrl;
    @Value("${integration.queryListOriginationUrl}")
    private String queryListOriginationUrl;
    @Value("${lisa.lspm.getDriverInfoById}")
    private String getDriverInfoById;
    @Value("${lisa.lspm.isUnlcnFleetDriverUrl}")
    private String isUnlcnFleetDriverUrl;
    @Value("${lisa.lspm.queryDriverWithFleet}")
    private String queryDriverWithFleet;
    @Value("${lisa.bms.deletePurchaseUrl}")
    private String deletePurchaseUrl;

    /**
     * 同步人送指令 -- 含价格
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void shipInfoSync(HuiyuncheShipInfoDTO infoDTO, String auth) {
        //重复校验  -- 生成lisa-order --生成 shiporder  生成 shipment  --shipmentdetail
        //String token = StringUtils.substringAfter(auth, "Bearer ");
        //JwtAccountVO accountVO = JwtTokenUtil.decodeJwt(token);
        //Long tenantId = Long.valueOf(accountVO.getTenantId());
        Long tenantId=null;
        if (infoDTO != null) {
            //infoDTO.setTenantId(tenantId);
            EntityWrapper<Order> orderEW = new EntityWrapper<>();
            orderEW.eq("customer_id", TableStatusEnum.STATUS_HUIYUNCHE_SYS.getCode())
                    .eq("customer_order_id", infoDTO.getVcorderno())
                    .eq("is_delete", TableStatusEnum.STATUS_0.getCode());
            int count = orderService.selectCountNotenant(orderEW);
            if (count > 0) {
                logger.info("人送指令号 {},已经存在...", infoDTO.getVcorderno());
            } else {
                //新增指令
                //根据司机手机号获取lspid等信息
                ArrayList<NameValuePair> hearders = Lists.newArrayList();
                hearders.add(new BasicNameValuePair("Authorization", auth));
                try {
                    logger.info("人送-->获取司机信息 url:{},param:{}", queryDriverWithFleet, infoDTO.getDriverPhone());
                    String res = HttpClientUtil.get(queryDriverWithFleet + "/" + infoDTO.getDriverPhone(), hearders, null, socketTimeout);
                    logger.info("人送-->获取司机信息 param:{}, result:{}", infoDTO.getDriverPhone(), res);
                    if (StringUtils.isNotBlank(res)) {
                        JSONObject response = JSONObject.parseObject(res);
                        JSONObject data = response.getJSONObject("data");
                        int code = response.getIntValue("code");
                        if (code != 0) {
                            throw new BaseException(response.getString("message"));
                        } else if (data != null) {
                            Long lspId = data.getLong("lspId");
                            String lspName = data.getString("lspName");
                            String id = data.getString("id");
                            String name = data.getString("name");
                            String fleetId = data.getString("fleetId");
                            String fleetName = data.getString("fleetName");
                            tenantId = data.getLong("tenantId");
                            infoDTO.setDriverName(name);
                            infoDTO.setDriverId(id);
                            if (StringUtils.isNotBlank(fleetId)) {
                                infoDTO.setFleetId(fleetId);
                                infoDTO.setFleetName(fleetName);
                            }
                            infoDTO.setLspId(String.valueOf(lspId));
                            infoDTO.setLspName(lspName);
                            infoDTO.setTenantId(tenantId);
                        }
                    } else {
                        throw new BaseException("根据司机手机号获取LSPID未响应,请稍后再试");
                    }
                } catch (Exception e) {
                    logger.error("人送根据司机手机号获取LSPID连接失败:{}", e);
                    throw new BaseException("根据司机手机号获取LSPID失败,请稍后再试");
                }
                //获取目的地编码(省 + 市)
                LocationVo endLocation = getEndLocationVo(infoDTO, auth);
                //获取启运地
                LocationVo startLocation = getStartLocation(infoDTO, auth);
                //获取运输方式
                Long transTypeId = orderService.getTransTypeId(infoDTO.getVctransname());
                infoDTO.setTransTypeId(transTypeId);
                //oms订单逻辑
                Order order = getOrder(infoDTO, tenantId, transTypeId);
                //order item
                OrderItem item = getOrderItem(infoDTO, tenantId,order);
                ArrayList<OrderItem> items = Lists.newArrayList();
                items.add(item);
                order.setOrderItemList(items);
                // order  contact
                OrderContact orderContact = getOrderContact(infoDTO, tenantId, order);
                order.setOrderContact(orderContact);
                //orderlocation
                OrderLocation orderLocation = getOrderLocation(tenantId, endLocation, startLocation, order);
                order.setOrderLocation(orderLocation);
                infoDTO.setOrder(order);
                //获取标准价
                //Map<String, BigDecimal> otmRes = priceAndMiles(infoDTO.getVcorderno(), auth);
                // tms
                List<OrderAssignDTO> dtoList = shipOrderService.addHuiyuncheShipment(infoDTO, auth, null);
                // 回写下发单委托单号（下游系统回写单号）
                if (CollectionUtils.isNotEmpty(dtoList)) {
                    for (OrderAssignDTO orderAssignDTO : dtoList) {
                        getOrderAssign(tenantId, order, orderAssignDTO);
                    }
                }
                PriceIncomingDTO priceIncomingDTO = new PriceIncomingDTO();
                priceIncomingDTO.setTenantId(tenantId);
                priceIncomingDTO.setOrderCode(order.getCode());
                priceIncomingDTO.setCustomerId(TableStatusEnum.STATUS_HUIYUNCHE_SYS.getCode());
                priceIncomingDTO.setCustomerName("中联物流-人送");
                //priceIncomingDTO.setItemSourceKey();
                priceIncomingDTO.setOrderItemId(item.getId());
                //暂估价
                //priceIncomingDTO.setEstIncomingPrice(otmRes.get("price"));
                //计价里程
                //priceIncomingDTO.setMileage(otmRes.get("miles"));
                //车架号
                priceIncomingDTO.setItemUid(infoDTO.getVcvin());
                //车型信息
                priceIncomingDTO.setVehicleTypeCode(StringUtils.isBlank(infoDTO.getVcstylename()) ? infoDTO.getVehicledesc() : infoDTO.getVcstylename());
                priceIncomingDTO.setDepartLocationId(startLocation.getId());
                priceIncomingDTO.setDepartLocationAdCode(startLocation.getAdCode());
                priceIncomingDTO.setDepartAdressName(startLocation.getValue());
                priceIncomingDTO.setDepartAddressName(startLocation.getValue());
                priceIncomingDTO.setTransTypeId(Long.valueOf(CodePrefixEnum.PEOPLESEND.getFix()));
                priceIncomingDTO.setDestLocationId(endLocation.getId());
                priceIncomingDTO.setDestLocationAdCode(endLocation.getAdCode());
                priceIncomingDTO.setDestAdderssName(infoDTO.getVcaddress());
                priceIncomingDTO.setCreateFrom(TableStatusEnum.STATUS_20.getCode());//10-OTM，20-人送，30-其他
                priceIncomingDTO.setStartProvince(infoDTO.getVcstartprovince());
                priceIncomingDTO.setStartCity(infoDTO.getVcstartcity());
                priceIncomingDTO.setEndProvince(infoDTO.getVcprovincename());
                priceIncomingDTO.setEndCity(infoDTO.getVccityname());
                priceIncomingDTO.setVehicleClassifyId(infoDTO.getIstyleid());
                List<NameValuePair> headNamePairs = Lists.newArrayList();
                headNamePairs.add(new BasicNameValuePair("Authorization", auth));
                try {
                    logger.info("人送指令-->连接BMS 生成收入单据url:{},param:{}", insertPriceIncomingUrl, JSON.toJSONString(priceIncomingDTO));
                    String result = HttpClientUtil.postJson(insertPriceIncomingUrl, headNamePairs, JSON.toJSONString(priceIncomingDTO), socketTimeout);
                    logger.info("人送指令-->连接BMS 生成收入单据result:{}", result);
                    if (StringUtils.isBlank(result)) {
                        logger.error("人送指令-->连接BMS生成收入单据失败 未响应---->{}", result);
                        throw new BaseException("人送指令-->连接BMS生成收入单据未响应,请稍后再试");
                    } else {
                        JSONObject parseObject = JSONObject.parseObject(result);
                        int code = parseObject.getIntValue("code");
                        if (code != 0) {
                            throw new BaseException("人送指令-->连接BMS收入失败" + parseObject.getString("message"));
                        }
                    }
                } catch (Exception e) {
                    logger.error("人送指令-->连接BMS生成收入单据失败 error:{}", e);
                    throw new BaseException("人送指令-->连接BMS生成收入单据失败,请稍后再试");
                }
            }
        }
    }

    /**
     * 获取价格跟里程 -标准价
     */
    private Map<String, BigDecimal> priceAndMiles(String orderNo, String authorization) {
        Map<String, BigDecimal> result = new HashMap<>();
        Map<String, String> orderno = new HashMap<>();
        orderno.put("orderno", orderNo);
        List<NameValuePair> headNamePairs = Lists.newArrayList();
        headNamePairs.add(new BasicNameValuePair("Authorization", authorization));
        String priceAndMiles = HttpClientUtil.postJson(integrationUrl + getPriceAndMilesUrl, headNamePairs,
                JSON.toJSONString(orderno), socketTimeout);
        logger.info("人送标准价--->priceAndMiles url:{},param:{}, result {}", integrationUrl + getPriceAndMilesUrl, JSON.toJSONString(orderno), priceAndMiles);
        if (StringUtils.isNotBlank(priceAndMiles)) {
            JSONObject parseObject = JSONObject.parseObject(priceAndMiles);
            if (parseObject.getIntValue("code") == 0) {
                //暂估价
                JSONObject data = parseObject.getJSONObject("data");
                if (data != null) {
                    result.put("price", data.getBigDecimal("price"));
                    //计价里程
                    result.put("miles", data.getBigDecimal("miles"));
                }
            } else {
                logger.error("人送标准价--->获取价格里程失败" + parseObject.getString("message"));
            }
        } else {
            logger.error("人送标准价--->连接OTM获取价格里程失败");
        }

        return result;
    }


    private void getOrderAssign(Long tenantId, Order order, OrderAssignDTO orderAssignDTO) {
        OrderAssign orderAssign = new OrderAssign();
        orderAssign.setOrderCode(order.getCode());
        orderAssign.setOrderItemCode(orderAssignDTO.getOrderItemCode());
        orderAssign.setGmtAssign(new Date());
        orderAssign.setAssignLog("成功");
        orderAssign.setGmtConsign(new Date());
        orderAssign.setConsignCode(orderAssignDTO.getConsignCode());
        orderAssign.setTenantId(tenantId);
        assignService.insert(orderAssign);
    }

    private OrderLocation getOrderLocation(Long tenantId, LocationVo endLocation, LocationVo startLocation, Order order) {
        OrderLocation orderLocation = new OrderLocation();
        orderLocation.setOrderId(order.getId());
        orderLocation.setShippingLocationId(endLocation.getId());
        orderLocation.setDeliveryLocationId(startLocation.getId());
        orderLocation.setGmtCreate(new Date());
        orderLocation.setTenantId(tenantId);
        orderLocation.setDeliveryLocationName(startLocation.getValue());
        orderLocation.setShippingLocationName(endLocation.getValue());
        orderLocationService.insert(orderLocation);
        return orderLocation;
    }

    private OrderContact getOrderContact(HuiyuncheShipInfoDTO infoDTO, Long tenantId, Order order) {
        OrderContact orderContact = new OrderContact();
        orderContact.setContactsName(infoDTO.getDriverName());
        orderContact.setContactsPhone(infoDTO.getDriverPhone());
        orderContact.setOrderCode(order.getCode());
        orderContact.setTenantId(tenantId);
        contactService.insert(orderContact);
        return orderContact;
    }

    private OrderItem getOrderItem(HuiyuncheShipInfoDTO infoDTO, Long tenantId,Order order) {
        OrderItem item = new OrderItem();
        item.setOrderId(order.getId());
        item.setItemSourceKey(infoDTO.getVcorderno());
        item.setAmount(1);
        item.setUom("辆");
        item.setIssueItemId(infoDTO.getVcvin());
        item.setCurrentStatus("1");
        item.setOwnerId(0L);
        item.setOwnerName(infoDTO.getVcdealername());
        item.setGmtCreate(new Date());
        item.setTenantId(tenantId);
        item.setMaterial(infoDTO.getVcstylename());
        itemService.insert(item);
        return item;
    }

    private Order getOrder(HuiyuncheShipInfoDTO infoDTO, Long tenantId, Long transTypeId) {
        Order order = new Order();
        order.setCode("CO" + snowFlakeId.nextId());
        order.setComment(infoDTO.getMemo());
        order.setCustomerId(TableStatusEnum.STATUS_HUIYUNCHE_SYS.getCode());
        order.setTos("driver");
        order.setGmtIssue(new Date());
        order.setGmtCreate(new Date());
        order.setCustomerOrderId(infoDTO.getVcorderno());
        order.setTransTypeId(transTypeId);
        order.setTenantId(tenantId);
        order.setCurrentStatus("");
        order.setCustomerId("huiyunche");
        order.setCustomerName("中联物流-人送");
        order.setTransTypeId(6l);
        orderService.insert(order);
        return order;
    }

    private LocationVo getStartLocation(HuiyuncheShipInfoDTO infoDTO, String auth) {
        String startProvince = infoDTO.getVcstartprovince();
        String startCity = infoDTO.getVcstartcity();
        String startAdd = formatProvinceCity(startProvince, startCity);
        LocationVo startLocation = locationService.getLocationByValue("发货点", startAdd);
        if (startLocation == null) {
            List<NameValuePair> headNamePairs = Lists.newArrayList();
            headNamePairs.add(new BasicNameValuePair("Authorization", auth));
            Map<String, String> params = new HashMap<>();
            params.put("province", startProvince);
            params.put("city", startCity);
            String result = null;
            try {
                logger.info("人送指令--连接Integration 获取启运地编码 url:{} param:{}", integrationUrl + queryListOriginationUrl, JSONObject.toJSONString(params));
                result = HttpClientUtil.postJson(integrationUrl + queryListOriginationUrl, headNamePairs, JSONObject.toJSONString(params), socketTimeout);
                logger.info("人送指令--连接Integration 获取启运地编码 url:{} result:{}", integrationUrl + queryListOriginationUrl, result);
                if (StringUtils.isBlank(result)) {
                    logger.error("人送指令--连接Integration 获取启运地编码未响应 error");
                }
            } catch (Exception e) {
                logger.error("人送指令--连接Integration 获取启运地编码失败 error:{}", e);
            }
            JSONObject jsonObject = JSONObject.parseObject(result);
            if (Objects.nonNull(jsonObject)) {
                String data = jsonObject.getString("data");
                if (!StringUtils.isEmpty(data)) {
                    List<OriginationDTO> originationDTOS = JSONObject.parseArray(data, OriginationDTO.class);
                    if (StringUtils.isNotBlank(originationDTOS.get(0).getCountyCode())) {
                        // 调整省市区 组装code
                        startLocation = locationService.insertOrUpdateLocation("发货点",
                                startAdd, startAdd, originationDTOS.get(0).getCountyCode(), Long.valueOf(infoDTO.getTenantId()));
                    } else {
                        startLocation = locationService.insertOrUpdateLocation("发货点",
                                startAdd, startAdd, originationDTOS.get(0).getCityCode(), Long.valueOf(infoDTO.getTenantId()));
                    }
                }

            }
        }
        if (startLocation == null) {
            logger.error("未获取启运地编码--->省:{},市:{}", infoDTO.getVcstartprovince(), infoDTO.getVcstartcity());
            throw new BaseException("未获取启运地编码-->省:{},市:{}" + infoDTO.getVcstartprovince() + infoDTO.getVcstartcity());
        }
        startLocation.setProvince(startProvince);
        startLocation.setCity(startCity);
        infoDTO.setStartLocation(startLocation);
        return startLocation;
    }

    private LocationVo getEndLocationVo(HuiyuncheShipInfoDTO infoDTO, String auth) {
        String destProvince = infoDTO.getVcprovincename();
        String destCity = infoDTO.getVccityname();
        String destAdd = formatProvinceCity(destProvince, destCity);
        // 判断订单明细里的交货地点信息是否存在，不存在则插入
        LocationVo endLocation = locationService.getLocationByValue("交货点", destAdd);
        if (endLocation == null) {
            Map<String, String> params = new HashMap<>();
            params.put("province", destProvince);
            params.put("city", destCity);
            List<NameValuePair> headNamePairs = Lists.newArrayList();
            headNamePairs.add(new BasicNameValuePair("Authorization", auth));
            String result = null;
            try {
                logger.info("人送指令--连接Integration 获取的地编码 url:{} param:{}", integrationUrl + queryListOriginationUrl, JSONObject.toJSONString(params));
                result = HttpClientUtil.postJson(integrationUrl + queryListOriginationUrl, headNamePairs, JSONObject.toJSONString(params), socketTimeout);
                logger.info("人送指令--连接Integration 获取的地编码 url:{} result:{}", integrationUrl + queryListOriginationUrl, result);
                if (StringUtils.isBlank(result)) {
                    logger.error("人送指令--连接Integration 获取目的地编码未响应 error");
                }
            } catch (Exception e) {
                logger.error("人送指令--连接Integration 获取目的地编码失败 error:{}", e);
            }
            JSONObject jsonObject = JSONObject.parseObject(result);
            if (Objects.nonNull(jsonObject)) {
                String data = jsonObject.getString("data");
                if (!StringUtils.isEmpty(data)) {
                    List<OriginationDTO> originationDTOS = JSONObject.parseArray(data, OriginationDTO.class);
                    if (StringUtils.isNotBlank(originationDTOS.get(0).getCountyCode())) {
                        // 调整省市区 组装code
                        endLocation = locationService.insertOrUpdateLocation("交货点",
                                destAdd, destAdd, originationDTOS.get(0).getCountyCode(), Long.valueOf(infoDTO.getTenantId()));
                    } else {
                        endLocation = locationService.insertOrUpdateLocation("交货点",
                                destAdd, destAdd, originationDTOS.get(0).getCityCode(), Long.valueOf(infoDTO.getTenantId()));
                    }
                }

            }
        }
        if (endLocation == null) {
            logger.error("未获取目的地编码--->省:{},市:{}", infoDTO.getVcprovincename(), infoDTO.getVccityname());
            throw new BaseException("未获取目的地编码-->省:{},市:{}" + infoDTO.getVcprovincename() + infoDTO.getVccityname());
        }
        endLocation.setProvince(destProvince);
        endLocation.setCity(destCity);
        infoDTO.setEndLocation(endLocation);
        return endLocation;
    }

    /**
     * 人送指令退单
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancelShip(HuiyuncheCancleDTO infoDTO, String auth) {
        //重复校验  -- 退单lisa-order --退单 shiporder  退单 shipment  --shipmentdetail
        //String token = StringUtils.substringAfter(auth, "Bearer ");
        //JwtAccountVO accountVO = JwtTokenUtil.decodeJwt(token);
       // Long tenantId = Long.valueOf(accountVO.getTenantId());
        if (infoDTO == null) {
            throw new BaseException("参数不能为空");
        }
        String vcorderno = infoDTO.getOrderCode();
        if (StringUtils.isNotBlank(vcorderno)) {
            //重复校验
            EntityWrapper<Order> ew = new EntityWrapper<>();
            ew.eq("customer_id", TableStatusEnum.STATUS_HUIYUNCHE_SYS.getCode())
                    .eq("customer_order_id", infoDTO.getOrderCode())
                    .eq("is_delete", TableStatusEnum.STATUS_0.getCode())
                    .orderBy("id", false);
            Order order = orderService.selectOneNotenant(ew);
            if (order != null) {
                EntityWrapper<OrderItem> itemEW = deleteOms(order);
                //tms
                EntityWrapper<OrderAssign> asEW = new EntityWrapper<>();
                asEW.eq("order_code", order.getCode())
                        .eq("is_delete", TableStatusEnum.STATUS_0.getCode());
                List<OrderAssign> assigns = assignService.selectListNotenant(asEW);
                ArrayList<String> sos = Lists.newArrayList();
                if (CollectionUtils.isNotEmpty(assigns)) {
                    for (OrderAssign oa : assigns) {
                        sos.add(oa.getConsignCode());
                    }
                    EntityWrapper<ShipOrder> soEW = new EntityWrapper<>();
                    soEW.in("code", sos);
                    shipOrderService.delete(soEW);
                    EntityWrapper<ShipOrderItem> soIEW = new EntityWrapper<>();
                    soIEW.in("ship_order_code", sos)
                            .eq("is_delete", TableStatusEnum.STATUS_0.getCode());
                    List<ShipOrderItem> items = shipOrderItemService.selectListNotenant(soIEW);
                    shipOrderItemService.delete(soIEW);

                    EntityWrapper<ShipTask> taskEW = new EntityWrapper<>();
                    taskEW.in("ship_order_code", sos)
                            .eq("is_delete", TableStatusEnum.STATUS_0.getCode());
                    List<ShipTask> tasks = taskService.selectListNoTenant(taskEW);
                    HashSet<String> ts = Sets.newHashSet();
                    if (CollectionUtils.isNotEmpty(tasks)) {
                        for (ShipTask st : tasks) {
                            ts.add(st.getCode());
                        }
                        taskService.delete(taskEW);
                    }
                    //shipment shipmentDetail
                    EntityWrapper<ShipmentDetail> sdEW = new EntityWrapper<>();
                    sdEW.in("ship_task_code", ts)
                            .eq("is_delete", TableStatusEnum.STATUS_0.getCode());
                    List<ShipmentDetail> sds = shipmentDetailService.selectListNoTenant(sdEW);
                    HashSet<Long> ds = Sets.newHashSet();
                    if (CollectionUtils.isNotEmpty(sds)) {
                        for (ShipmentDetail sd : sds) {
                            ds.add(sd.getShipmentId());
                        }
                        EntityWrapper<Shipment> sew = new EntityWrapper<>();
                        sew.in("id", ds)
                                .eq("is_delete", TableStatusEnum.STATUS_0.getCode());
                        List<Shipment> shipments = shipmentService.selectListNotenant(sew);
                        if (CollectionUtils.isNotEmpty(shipments)) {
                            for (ShipOrderItem soi : items) {
                                //BMS同步删除
                                purchaseDelete(auth, tasks, shipments, soi);
                            }
                        }
                        shipmentService.delete(sew);
                        shipmentDetailService.delete(sdEW);
                    }
                }
                EntityWrapper<OrderAssign> assEW = new EntityWrapper<>();
                assEW.eq("order_code", order.getCode())
                        .eq("is_delete", TableStatusEnum.STATUS_0.getCode());
                assignService.delete(assEW);
                //BMS同步删除
                incomingDelete(auth, null, order);
            }
        }
    }

    private void incomingDelete(String auth, Long tenantId, Order order) {
        PriceIncomingDTO priceIncomingDTO = new PriceIncomingDTO();
        priceIncomingDTO.setOrderCode(order.getCode());
        priceIncomingDTO.setCreator(tenantId);
        List<NameValuePair> headNamePairs = Lists.newArrayList();
        headNamePairs.add(new BasicNameValuePair("Authorization", auth));
        logger.info("人送退单--> 删除指令调用BMS 删除接口--->url:{},priceIncomingDTO:{}",
                deletePriceIncomingUrl, JSON.toJSONString(priceIncomingDTO));
        String strReturn = null;
        try {
            strReturn = HttpClientUtil.postJson(deletePriceIncomingUrl, headNamePairs,
                    JSON.toJSONString(priceIncomingDTO), socketTimeout);
            logger.info("人送退单--> result:{}", strReturn);
        } catch (Exception e) {
            logger.error("人送退单--> 连接BMS失败:{}", e);
        }
    }

    private void purchaseDelete(String auth, List<ShipTask> tasks, List<Shipment> shipments, ShipOrderItem soi) {
        PricePurchaseDTO pricePurchaseDTO = new PricePurchaseDTO();
        pricePurchaseDTO.setShipmentCode(shipments.get(0).getCode());
        pricePurchaseDTO.setShipTaskCode(tasks.get(0).getCode());
        pricePurchaseDTO.setShipOrderItemId(soi.getId());
        List<NameValuePair> headNamePairs = Lists.newArrayList();
        headNamePairs.add(new BasicNameValuePair("Authorization", auth));
        try {
            logger.info("人送退单-->连接BMS 删除支付单据url:{},param:{}", deletePurchaseUrl, JSON.toJSONString(pricePurchaseDTO));
            String json = HttpClientUtil.postJson(deletePurchaseUrl, headNamePairs,
                    JSON.toJSONString(pricePurchaseDTO), socketTimeout);
            logger.info("人送退单--> result:{}", json);
        } catch (Exception e) {
            logger.error("人送退单--> 超时失败: {}", e);
        }
    }

    private EntityWrapper<OrderItem> deleteOms(Order order) {
        orderService.deleteById(order.getId());
        EntityWrapper<OrderItem> itemEW = new EntityWrapper<>();
        itemEW.eq("order_id", order.getId())
                .eq("is_delete", TableStatusEnum.STATUS_0.getCode());
        itemService.delete(itemEW);
        EntityWrapper<OrderContact> conEW = new EntityWrapper<>();
        conEW.eq("order_code", order.getCode())
                .eq("is_delete", TableStatusEnum.STATUS_0.getCode());
        contactService.delete(conEW);
        EntityWrapper<OrderLocation> locEW = new EntityWrapper<>();
        locEW.eq("order_id", order.getId())
                .eq("is_delete", TableStatusEnum.STATUS_0.getCode());
        orderLocationService.delete(locEW);
        return itemEW;
    }

    private String formatProvinceCity(String province, String city) {
        if (StringUtils.isNotBlank(city)) {
            if (!(city.endsWith("市") || city.endsWith("州"))) {
                city = city.concat("市");
            }
        }
        String startAdd = null;
        if (StringUtils.isNotBlank(province)) {
            if (!(province.endsWith("省") || province.endsWith("区"))) {
                switch (province) {
                    case "重庆":
                        province = "重庆市";
                        break;
                    case "上海":
                        province = "上海市";
                        break;
                    case "北京":
                        province = "北京市";
                        break;
                    case "天津":
                        province = "天津市";
                        break;
                    default:
                        province = province.concat("省");
                        break;
                }
            }
            startAdd = province.concat(city);
        } else {
            //直辖市处理
            province = city;
            startAdd = province.concat(city);
        }
        return startAdd;
    }
}
